package com.chzye.xhanddemos;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.rokid.gd.TempratureCallback;

/**
 * GD红外测温Activity Java版本
 * 移植自rokid_apg_xhands项目
 */
public class GdActivityJava extends AppCompatActivity implements TempratureCallback {

    private static final String TAG = "GdActivityJava";

    private GdTemplateInfraCameraViewJava infraCameraView;
    private TextView centerTempTextView;
    private TextView highTempTextView;
    private TextView lowTempTextView;
    private TextView tempBarHighTextView;
    private TextView tempBarLowTextView;
    private Button captureButton;
    private Button settingsButton;
    private LinearLayout tempBarLayout;

    // 设置选项
    private boolean isIronRedMode = true; // 铁红模式
    private int measureDistance = 50; // 测温距离
    private boolean isAnalysisMode = false; // 分析模式

    // 距离选项
    private final int[] distances = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
    private int distanceIndex = 4; // 默认50
    


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gd_java);
        
        initViews();
        
        // 直接初始化摄像头，权限已在MainActivity中检查
        initCamera();
    }

    private void initViews() {
        infraCameraView = findViewById(R.id.infra_camera_view_java);
        centerTempTextView = findViewById(R.id.center_temp_tv);
        highTempTextView = findViewById(R.id.high_temp_tv);
        lowTempTextView = findViewById(R.id.low_temp_tv);
        tempBarHighTextView = findViewById(R.id.temp_bar_hig_tv);
        tempBarLowTextView = findViewById(R.id.temp_bar_low_tv);
        captureButton = findViewById(R.id.capture_btn);
        settingsButton = findViewById(R.id.settings_btn);
        tempBarLayout = findViewById(R.id.temp_bar_ll);

        // 设置温度显示TextView的引用
        infraCameraView.setTemperatureTextViews(
                centerTempTextView,
                highTempTextView,
                lowTempTextView,
                tempBarHighTextView,
                tempBarLowTextView
        );

        // 设置温度回调
        infraCameraView.setTemperatureCallback(this);

        // 拍照按钮
        captureButton.setOnClickListener(v -> {
            boolean success = infraCameraView.capturePhoto();
            if (success) {
                Toast.makeText(this, "拍照成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "拍照失败", Toast.LENGTH_SHORT).show();
            }
        });

        // 设置按钮
        settingsButton.setOnClickListener(v -> showSettings());
    }


    
    private void initCamera() {
        try {
            // 初始化红外摄像头
            infraCameraView.initInfraCamera();
            
            // 设置默认测温距离
            infraCameraView.setMeasureDistance(measureDistance);
            
            Log.d(TAG, "红外摄像头初始化完成");
            Toast.makeText(this, "红外摄像头初始化成功", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Log.e(TAG, "红外摄像头初始化失败", e);
            Toast.makeText(this, "红外摄像头初始化失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    private void showSettings() {
        String[] options = {
                "切换色彩模式 (当前: " + (isIronRedMode ? "铁红" : "其他") + ")",
                "设置测温距离 (当前: " + distances[distanceIndex] + ")",
                "切换分析模式 (当前: " + (isAnalysisMode ? "开启" : "关闭") + ")"
        };

        new AlertDialog.Builder(this)
                .setTitle("设置选项")
                .setItems(options, (dialog, which) -> {
                    switch (which) {
                        case 0:
                            // 切换色彩模式
                            isIronRedMode = !isIronRedMode;
                            infraCameraView.switchColorMode(isIronRedMode);
                            Toast.makeText(this, "切换到" + (isIronRedMode ? "铁红" : "其他") + "模式", Toast.LENGTH_SHORT).show();
                            break;
                        case 1:
                            // 设置测温距离
                            showDistanceDialog();
                            break;
                        case 2:
                            // 切换分析模式
                            isAnalysisMode = !isAnalysisMode;
                            if (isAnalysisMode) {
                                infraCameraView.setAnalysisRegion(100, 100, 200, 200);
                                infraCameraView.toggleAnalysisBox(true);
                            } else {
                                infraCameraView.toggleAnalysisBox(false);
                            }
                            Toast.makeText(this, "分析模式" + (isAnalysisMode ? "开启" : "关闭"), Toast.LENGTH_SHORT).show();
                            break;
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void showDistanceDialog() {
        String[] distanceStrings = new String[distances.length];
        for (int i = 0; i < distances.length; i++) {
            distanceStrings[i] = distances[i] + "cm";
        }

        new AlertDialog.Builder(this)
                .setTitle("选择测温距离")
                .setSingleChoiceItems(distanceStrings, distanceIndex, (dialog, which) -> {
                    distanceIndex = which;
                    measureDistance = distances[distanceIndex];
                    infraCameraView.setMeasureDistance(measureDistance);
                    Toast.makeText(this, "测温距离设置为: " + measureDistance + "cm", Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    @Override
    public void callBack(float center, float hig, float low) {
        runOnUiThread(() -> {
            Log.d(TAG, String.format("温度回调 - 中心: %.1f°C, 最高: %.1f°C, 最低: %.1f°C", center, hig, low));
            
            // 更新温度显示
            if (centerTempTextView != null) {
                centerTempTextView.setText(String.format("中心温: %.1f°C", center));
            }
            if (highTempTextView != null) {
                highTempTextView.setText(String.format("最高温: %.1f°C", hig));
            }
            if (lowTempTextView != null) {
                lowTempTextView.setText(String.format("最低温: %.1f°C", low));
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "Activity resumed");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "Activity paused");
    }


    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        
        if (infraCameraView != null) {
            infraCameraView.release();
        }
        Log.d(TAG, "Activity destroyed");
    }

    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(this)
                .setTitle("退出")
                .setMessage("确定要退出红外测温吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    super.onBackPressed();
                })
                .setNegativeButton("取消", null)
                .show();
    }
}